import React, { useState, useEffect, useRef } from "react";
import { Card, Col, Row, Statistic, message, Button, Select } from "antd";
import * as echarts from "echarts";
import { api } from "../api";
import { useSelector, useDispatch } from 'react-redux';
import {
  setAttackerCount,
  setServerCount,
  addTrafficChart,
  updateTrafficChart,
  removeTrafficChart as removeTrafficChartAction
} from '../store/slices/networkSlice';
import AttackVerification from "../components/AttackVerification";

const { Option } = Select;

const NetworkMonitor = () => {
  // 使用Redux存储状态
  const dispatch = useDispatch();
  const { attackerCount, serverCount, trafficCharts, topologyData } = useSelector(state => state.network);

  // 本地状态只保留UI相关的状态
  const [loading, setLoading] = useState(false);
  const [selectedServer, setSelectedServer] = useState(null);
  const chartInstancesRef = useRef({});
  const intervalsRef = useRef({});

  useEffect(() => {
    // 组件挂载时获取一次数据
    fetchCounts();
    // 组件卸载时清除所有定时器
    return () => {
      Object.values(intervalsRef.current).forEach(interval => {
        clearInterval(interval);
      });
      // 销毁所有图表实例
      Object.values(chartInstancesRef.current).forEach(chart => {
        chart.dispose();
      });
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 当trafficCharts变化时，更新图表
  useEffect(() => {
    // 确保trafficCharts是数组
    if (Array.isArray(trafficCharts)) {
      trafficCharts.forEach(chart => {
        renderTrafficChart(chart);
      });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [trafficCharts]);

  // 获取服务器列表
  const getServerList = () => {
    if (!topologyData || !Array.isArray(topologyData.nodes)) return [];
    return topologyData.nodes
      .filter(node => node.type === "server")
      .map(node => node.name);
  };

  // 获取攻击者列表
  const getAttackerList = () => {
    if (!topologyData || !Array.isArray(topologyData.nodes)) return [];
    return topologyData.nodes
      .filter(node => node.type === "attacker")
      .map(node => node.name);
  };

  const fetchCounts = async () => {
    setLoading(true);
    try {
      console.log('正在获取网络状态...');

      // 分别处理两个请求，不要让一个失败影响另一个
      try {
        const attackerRes = await api.getAttackerCount();
        console.log('攻击者数量响应:', attackerRes);

        if (attackerRes.code === 0 || attackerRes.code === 200) {
          // 打印原始数据，帮助调试
          console.log('攻击者响应数据:', JSON.stringify(attackerRes));
          console.log('攻击者数据类型:', typeof attackerRes.data, '值:', attackerRes.data);

          // 直接使用data字段的值，不进行复杂的类型判断
          let parsedAttackerCount = 0;

          // 简单地检查data是否存在且不为null或undefined
          if (attackerRes.data !== null ) {
            // 尝试将data转换为数字
            parsedAttackerCount = Number(attackerRes.data.data);
            // 如果转换结果是NaN，则使用0
            if (isNaN(parsedAttackerCount)) {
              parsedAttackerCount = 0;
              console.error('攻击者数量转换为数字失败:', attackerRes.data);
            }
          }

          // 打印日志，帮助调试
          console.log('攻击者数据:', attackerRes.data, '处理后:', parsedAttackerCount);

          // 更新Redux状态
          dispatch(setAttackerCount(parsedAttackerCount));
        } else {
          console.error("获取攻击者数量失败:", attackerRes);
        }
      } catch (error) {
        console.error("获取攻击者数量错误:", error);
      }

      try {
        const serverRes = await api.getServerCount();
        console.log('服务器数量响应:', serverRes);

        if (serverRes.code === 0 || serverRes.code === 200) {
          // 打印原始数据类型，帮助调试
          console.log('服务器数据类型:', typeof serverRes.data, '值:', serverRes.data);

          // 直接使用data字段的值，不进行复杂的类型判断
          let parsedServerCount = 0;

          // 简单地检查data是否存在且不为null或undefined
          if (serverRes.data !== null ) {
            // 尝试将data转换为数字
            parsedServerCount = Number(serverRes.data.data);
            // 如果转换结果是NaN，则使用0
            if (isNaN(parsedServerCount)) {
              parsedServerCount = 0;
              console.error('服务器数量转换为数字失败:', serverRes.data);
            }
          }

          // 打印日志，帮助调试
          console.log('服务器数据:', serverRes.data, '处理后:', parsedServerCount);

          // 更新Redux状态
          dispatch(setServerCount(parsedServerCount));
        } else {
          console.error("获取服务器数量失败:", serverRes);
        }
      } catch (error) {
        console.error("获取服务器数量错误:", error);
      }

      message.success("网络状态刷新成功");
    } catch (error) {
      console.error("获取网络状态错误:", error);
      message.error("获取网络状态失败: " + (error.message || error));
    } finally {
      setLoading(false);
    }
  };

  const handleServerChange = (value) => {
    setSelectedServer(value);
  };

  const fetchServerTraffic = async () => {
    if (!selectedServer) {
      message.warning("请选择服务器");
      return;
    }

    setLoading(true);
    try {
      console.log('正在查询服务器流量:', selectedServer);
      const res = await api.getServerTraffic(selectedServer);
      console.log('服务器流量响应:', res);

      if (res.code === 0 || res.code === 200) {
        const trafficData = res.data.data;

        // 打印日志，帮助调试
        console.log('服务器流量数据:', trafficData);

        // 确保trafficData有正确的结构
        if (trafficData) {
          // 尝试提取服务器名称和流量数据
          const serverName = trafficData.serverName;
          const rxBytes = trafficData.rxBytes;
          const txBytes = trafficData.txBytes;

          console.log('处理后的流量数据:', { serverName, rxBytes, txBytes });

          // 检查是否已经存在该服务器的图表
          if (Array.isArray(trafficCharts) && trafficCharts.some((chart) => chart.serverName === serverName)) {
            message.warning("该服务器的实时图表已存在");
            return;
          }

          // 创建图表数据
          const chartData = {
            serverName,
            rxBytes: [{ time: new Date().toLocaleTimeString(), value: rxBytes }],
            txBytes: [{ time: new Date().toLocaleTimeString(), value: txBytes }],
          };

          // 添加到Redux
          dispatch(addTrafficChart(chartData));
          message.success("获取服务器流量成功");

          // 创建定时器获取实时数据
          const interval = setInterval(async () => {
            try {
              const res = await api.getServerTraffic(serverName);
              if (res.code === 0 || res.code === 200) {
                const data = res.data.data;
                if (data) {
                  const newRxBytes = data.rxBytes;
                  const newTxBytes = data.txBytes;

                  console.log(`实时流量更新 - ${serverName}:`, { rxBytes: newRxBytes, txBytes: newTxBytes });

                  dispatch(updateTrafficChart({
                    serverName,
                    rxBytes: newRxBytes,
                    txBytes: newTxBytes
                  }));
                }
              } else {
                console.error("获取实时流量失败:", res);
                clearInterval(intervalsRef.current[serverName]);
                delete intervalsRef.current[serverName];
              }
            } catch (error) {
              console.error("获取实时流量错误:", error);
              clearInterval(intervalsRef.current[serverName]);
              delete intervalsRef.current[serverName];
            }
          }, 1000);

          // 保存定时器引用
          intervalsRef.current[serverName] = interval;
        } else {
          message.error("服务器流量数据格式不正确");
          console.error("服务器流量数据为空:", trafficData);
        }
      } else {
        message.error(res.msg || "获取服务器流量失败");
        console.error("获取服务器流量失败:", res);
      }
    } catch (error) {
      console.error("获取服务器流量错误:", error);
      message.error("获取服务器流量失败: " + (error.message || error));
    } finally {
      setLoading(false);
    }
  };

  const renderTrafficChart = (chartData) => {
    const { serverName, rxBytes, txBytes } = chartData;
    const chartDom = document.getElementById(`chart-${serverName}`);
    if (!chartDom) return;
    // 如果已经有图表实例，先销毁
    if (chartInstancesRef.current[serverName]) {
      chartInstancesRef.current[serverName].dispose();
    }
    // 创建新的图表实例
    const chart = echarts.init(chartDom);
    chartInstancesRef.current[serverName] = chart;
    const option = {
      title: {
        text: `${serverName} 流量监控`,
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          let result = params[0].axisValue + '<br/>';
          params.forEach(param => {
            const value = (param.value / 1024).toFixed(2);
            result += `${param.seriesName}: ${value} KB<br/>`;
          });
          return result;
        }
      },
      legend: {
        data: ['接收流量', '发送流量'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: Array.isArray(rxBytes) ? rxBytes.map(item => item.time) : []
      },
      yAxis: {
        type: 'value',
        name: '流量 (bytes)',
        axisLabel: {
          formatter: function(value) {
            return (value / 1024).toFixed(2) + ' KB';
          }
        }
      },
      series: [
        {
          name: '接收流量',
          type: 'line',
          data: Array.isArray(rxBytes) ? rxBytes.map(item => item.value) : [],
          smooth: true,
          lineStyle: {
            width: 2,
            color: '#1890ff'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(24,144,255,0.3)' },
                { offset: 1, color: 'rgba(24,144,255,0.1)' }
              ]
            }
          }
        },
        {
          name: '发送流量',
          type: 'line',
          data: Array.isArray(txBytes) ? txBytes.map(item => item.value) : [],
          smooth: true,
          lineStyle: {
            width: 2,
            color: '#52c41a'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(82,196,26,0.3)' },
                { offset: 1, color: 'rgba(82,196,26,0.1)' }
              ]
            }
          }
        }
      ]
    };
    chart.setOption(option);
    // 窗口大小变化时重新调整图表大小
    const handleResize = () => {
      chart.resize();
    };

    window.addEventListener('resize', handleResize);

    // 返回清理函数
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  };
  const handleRemoveTrafficChart = (serverName) => {
    // 清除定时器
    if (intervalsRef.current[serverName]) {
      clearInterval(intervalsRef.current[serverName]);
      delete intervalsRef.current[serverName];
    }
    // 销毁图表实例
    if (chartInstancesRef.current[serverName]) {
      chartInstancesRef.current[serverName].dispose();
      delete chartInstancesRef.current[serverName];
    }
    // 从Redux状态中移除
    dispatch(removeTrafficChartAction(serverName));
  };

  return (
    <Row gutter={[16, 16]}>
      <Col span={8}>
        <Card title="网络状态监控" bordered loading={loading}>
          <Statistic
            title="攻击者数量"
            value={typeof attackerCount === 'number' ? attackerCount : 0}
            formatter={(value) => `${value}`}
          />
          <Statistic
            title="服务器数量"
            value={typeof serverCount === 'number' ? serverCount : 0}
            formatter={(value) => `${value}`}
            style={{ marginTop: "10px" }}
          />
          <div style={{ marginTop: "10px" }}>
            <Select
              showSearch
              style={{ width: "100%" }}
              placeholder="选择服务器"
              optionFilterProp="children"
              onChange={handleServerChange}
              value={selectedServer}
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {getServerList().map(server => (
                <Option key={server} value={server}>
                  {server}
                </Option>
              ))}
            </Select>
          </div>
          <Button
            type="primary"
            onClick={fetchServerTraffic}
            style={{ width: "100%", marginTop: "10px" }}
            loading={loading}
            disabled={!selectedServer}
          >
            查询流量
          </Button>
          <Button
            type="primary"
            onClick={fetchCounts}
            style={{ width: "100%", marginTop: "10px" }}
            loading={loading}
          >
            刷新网络状态
          </Button>
        </Card>
      </Col>

      <Col span={8}>
        <AttackVerification
          serverList={getServerList()}
          attackerList={getAttackerList()}
        />
      </Col>

      {Array.isArray(trafficCharts) && trafficCharts.map((chart) => (
        <Col span={24} key={chart.serverName}>
          <Card
            title={`实时流量 - ${chart.serverName}`}
            bordered
            extra={
              <Button type="text" danger onClick={() => handleRemoveTrafficChart(chart.serverName)}>
                关闭监控
              </Button>
            }
          >
            <div id={`chart-${chart.serverName}`} style={{ width: "100%", height: "300px" }}></div>
          </Card>
        </Col>
      ))}
    </Row>
  );
};

export default NetworkMonitor;
